package controller

import (
	"bytes"
	bc "fabric-test3/application/blockchain"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

//  创建一个新的公司
func CreateCompany(ctx *gin.Context) {
	// 解析请求体
	var company = make(map[string]string)
	companyType := ctx.Param("companyType")
	if companyType != "financial_org" && companyType != "supplier" && companyType != "buyer" {
		ctx.String(http.StatusNotFound, "Not found")
		return
	}
	err := ctx.ShouldBind(&company)
	if err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}

	resp, err := bc.ChannelExecute("createCompany", [][]byte{
		[]byte(companyType),
		[]byte(company["name"]),
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	// http返回
	ctx.JSON(http.StatusOK, resp)
}

//获取交易信息
func GetCompany(ctx *gin.Context) {
	companyType := ctx.Param("companyType")
	if companyType != "financial_org" && companyType != "supplier" && companyType != "buyer" {
		ctx.String(http.StatusNotFound, "Not found")
		return
	}

	resp, err := bc.ChannelQuery("getCompany", [][]byte{
		[]byte(companyType),
	})
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	// 将结果返回
	ctx.String(http.StatusOK, bytes.NewBuffer(resp.Payload).String())
}
